package com.xflib.shardingsphere.service.impl;

import com.xflib.shardingsphere.entity.User;
import com.xflib.shardingsphere.repository.UserRepository;
import com.xflib.shardingsphere.service.UserService;
import com.xflib.shardingsphere.utils.CustomBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户业务层接口实现类
 *
 * @author Jiahai
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User save(User user) {
//        if(null == user.getUserId()) {
//            user.setUserId((Long) CustomSnowFlakeUtils.getId(Long.class.getSimpleName()));
//        }
        user.setCreateTime(new Date());
        return userRepository.save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long userId) {
        userRepository.deleteById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User update(User user) {
        User userOriginal = userRepository.findById(user.getUserId())
                .orElseThrow(() -> new RuntimeException("ID不存在"))
                .setUserName(user.getUserName())
                .setSex(user.getSex())
                //.setCreateTime(user.getCreateTime())
                .setBirthday(user.getBirthday());
        CustomBeanUtils.copyPropertiesIgnoreNull(user, userOriginal);
        return userRepository.save(userOriginal);
    }

    @Override
    public User findById(Long userId) {
        return userRepository.findById(userId).orElseThrow(() -> new RuntimeException("ID不存在"));
    }

    @Override
    public List<User> list() {
        return userRepository.findAll(Sort.by(Sort.Direction.ASC, User.USER_ID));
    }

    @Override
    public Page<User> page(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page > 0 ? page - 1 : 0, size, Sort.by(Sort.Direction.DESC, User.USER_ID));
        return this.userRepository.findAll(pageRequest);
    }
}
